package com.frkj.yuan.main;
import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.RecyclerView;
import com.amap.api.maps.MapsInitializer;
import com.frkj.yuan.R;
import com.frkj.yuan.adapter.BaseRecyclerHolder;
import com.frkj.yuan.adapter.BaseRecyclerRefreshAdapter;
import com.frkj.yuan.api.bean.VersionBean;
import com.frkj.yuan.api.category.VersionCategory;
import com.frkj.yuan.api.presenter.VersionMsgPresenter;
import com.frkj.yuan.base.BaseActivity;
import com.frkj.yuan.dialog.CheckedUpdateVersionData;
import com.frkj.yuan.dialog.VersionDialog;
import com.frkj.yuan.fragment.my.MyFragment;
import com.frkj.yuan.fragment.order.OrderFragment;
import com.frkj.yuan.fragment.home.HomeNewFragment;
import com.frkj.yuan.utils.ToastUtil;
import com.frkj.yuan.view.RecyclerViewLayoutManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.BindView;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
public class MainActivity extends BaseActivity implements VersionCategory.View {
    private long exitTime = 0;
    @BindView(R.id.bottom_main)
    BottomNavigationView bottomMain;
    private MyFragment myFragment;
    private OrderFragment orderFragment;
    private HomeNewFragment homeFragment;
    private Fragment[] fragments;
    private int lastfragment = 0;
    //是否需要检测后台定位权限，设置为true时，如果用户没有给予后台定位权限会弹窗提示
    private boolean needCheckBackLocation = false;
    //如果设置了target > 28，需要增加这个权限，否则不会弹出"始终允许"这个选择框
    private static String BACK_LOCATION_PERMISSION = "android.permission.ACCESS_BACKGROUND_LOCATION";
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            BACK_LOCATION_PERMISSION
    };
    private static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;
    private VersionMsgPresenter mPresener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }
    @Override
    public void initLayoutView(){
        YCAppBar.setStatusBarColor(MainActivity.this,
                ContextCompat.getColor(MainActivity.this,
                        R.color.base_color));
        if(Build.VERSION.SDK_INT > 28
                && getApplicationContext().getApplicationInfo().targetSdkVersion > 28) {
            needPermissions = new String[] {
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE,
                    BACK_LOCATION_PERMISSION
            };
            needCheckBackLocation = true;
        }
        initLayout();
    }
    @Override
    protected void onResume() {
        try{
            super.onResume();
            if (Build.VERSION.SDK_INT >= 23) {
                if (isNeedCheck) {
                    checkPermissions(needPermissions);
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
    }
    private void initLayout() {
        // TODO: 2022/6/14 设置高德地图隐私权限
        MapsInitializer.updatePrivacyAgree(MainActivity.this, true);
        MapsInitializer.updatePrivacyShow(MainActivity.this, true, true);
        mPresener = new VersionMsgPresenter(this);
        SetPersenter(mPresener);
        updateVersion();
        homeFragment = new HomeNewFragment();
        orderFragment = new OrderFragment();
        myFragment = new MyFragment();
        fragments = new Fragment[]{homeFragment, orderFragment, myFragment};
        //设置fragment到布局
        getSupportFragmentManager().beginTransaction().replace(R.id.contentContainer, homeFragment).show(homeFragment).commit();
        //这里是bottomnavigationview的点击事件
        bottomMain.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    private void updateVersion() {
        String oldVersionName = null;
        try {
            oldVersionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        mPresener.getVersionMsg("v"+oldVersionName);
    }
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.home:
                    //这里因为需要对3个fragment进行切换
                    //start
                    if (lastfragment != 0) {
                        switchFragment(lastfragment, 0);
                        lastfragment = 0;
                    }
                    //end
                    //如果只是想测试按钮点击，不管fragment的切换，可以把start到end里面的内容去掉
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.base_color));
                    return true;
                case R.id.order:
                    if (lastfragment != 1) {
                        switchFragment(lastfragment, 1);
                        lastfragment = 1;
                    }
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.white_color));
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//黑色
                    return true;
                case R.id.my:
                    if (lastfragment != 2) {
                        switchFragment(lastfragment, 2);
                        lastfragment = 2;
                    }
                    YCAppBar.setStatusBarColor(MainActivity.this,
                            ContextCompat.getColor(MainActivity.this,
                                    R.color.white_color));
                    getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);//黑色
                    return true;
                default:
                    break;
            }
            return false;
        }
    };
    /**
     *切换fragment
     */
    private void switchFragment(int lastfragment, int index) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //隐藏上个Fragment
        transaction.hide(fragments[lastfragment]);
        if (fragments[index].isAdded() == false) {
            transaction.add(R.id.contentContainer, fragments[index]);
        }
        transaction.show(fragments[index]).commitAllowingStateLoss();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtil.showToastERROR(MainActivity.this, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                BaseApplication.removeALLActivity();
                System.exit(0);
            }
            return true;
        }
        return false;
    }
    /**
     * @param
     * @since 2.5.0
     */
    @TargetApi(23)
    private void checkPermissions(String... permissions) {
        try{
            if (Build.VERSION.SDK_INT >= 23 && getApplicationInfo().targetSdkVersion >= 23) {
                List<String> needRequestPermissonList = findDeniedPermissions(permissions);
                if (null != needRequestPermissonList
                        && needRequestPermissonList.size() > 0) {
                    try {
                        String[] array = needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]);
                        Method method = getClass().getMethod("requestPermissions", new Class[]{String[].class, int.class});
                        method.invoke(this, array, 0);
                    } catch (Throwable e) {

                    }
                }
            }

        }catch(Throwable e){
            e.printStackTrace();
        }
    }
    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    @TargetApi(23)
    private List<String> findDeniedPermissions(String[] permissions) {
        try{
            List<String> needRequestPermissonList = new ArrayList<String>();
            if (Build.VERSION.SDK_INT >= 23 && getApplicationInfo().targetSdkVersion >= 23) {
                for (String perm : permissions) {
                    if (checkMySelfPermission(perm) != PackageManager.PERMISSION_GRANTED
                            || shouldShowMyRequestPermissionRationale(perm)) {
                        if(!needCheckBackLocation
                                && BACK_LOCATION_PERMISSION.equals(perm)) {
                            continue;
                        }
                        needRequestPermissonList.add(perm);
                    }
                }
            }
            return needRequestPermissonList;
        }catch(Throwable e){
            e.printStackTrace();
        }
        return null;
    }
    private int checkMySelfPermission(String perm) {
        try {
            Method method = getClass().getMethod("checkSelfPermission", new Class[]{String.class});
            Integer permissionInt = (Integer) method.invoke(this, perm);
            return permissionInt;
        } catch (Throwable e) {
        }
        return -1;
    }

    private boolean shouldShowMyRequestPermissionRationale(String perm) {
        try {
            Method method = getClass().getMethod("shouldShowRequestPermissionRationale", new Class[]{String.class});
            Boolean permissionInt = (Boolean) method.invoke(this, perm);
            return permissionInt;
        } catch (Throwable e) {
        }
        return false;
    }
    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        try{
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
        return true;
    }
    @TargetApi(23)
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] paramArrayOfInt) {
        try{
            if (Build.VERSION.SDK_INT >= 23) {
                if (requestCode == PERMISSON_REQUESTCODE) {
                    if (!verifyPermissions(paramArrayOfInt)) {
                        isNeedCheck = false;
                    }
                }
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
    }

    /**
     * 启动应用的设置
     * @since 2.5.0
     */
    private void startAppSettings() {
        try{
            Intent intent = new Intent(
                    Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
    /**
     * 版本更新
     * @param versionBean
     */
    @Override
    public void getVersionMsg(VersionBean versionBean) {
        if (versionBean !=null){
            if (versionBean.getCode()==ConstantStaticUrl.SUCCESS_CODE){
                if (versionBean.getData()!=null){
                    if (versionBean.getData().isNeedUpdate()==true){
                        String str = versionBean.getData().getClientYbVersion().getContent();
                        String[] split = str.split("\\#");
                        List<String> mlist = Arrays.asList(split);
                        VersionDialog dialog = new VersionDialog(MainActivity.this);
                        dialog.show();
                        TextView vers_number = (TextView)dialog.findViewById(R.id.vers_number);
                        vers_number.setText(versionBean.getData().getClientYbVersion().getVersionCode());
                        RecyclerView mRecyclerView = (RecyclerView)dialog.findViewById(R.id.recycler_version);
                        RecyclerViewLayoutManager.setLinearVerticalManager(MainActivity.this,mRecyclerView);
                        mRecyclerView.setAdapter(new BaseRecyclerRefreshAdapter<String>(MainActivity.this, mlist, R.layout.item_version_view) {
                            @Override
                            public void convert(BaseRecyclerHolder holder, String item, int position, boolean isScrolling) throws IOException {
                                holder.setText(R.id.version_nmae,item);
                            }
                        });
                        dialog.findViewById(R.id.submit_update).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckedUpdateVersionData checkedUpData = new CheckedUpdateVersionData();
                                checkedUpData.updata(MainActivity.this,versionBean.getData().getClientYbVersion().getDownloadUrl());
                                dialog.dismiss();
                            }
                        });
                        dialog.findViewById(R.id.icon_delete).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                    }
                }
            }else {
                ToastUtil.showToastINFO(MainActivity.this,versionBean.getMsg());
            }
        }
    }
    @Override
    public void SetPersenter(Object persenter) {}
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {

    }
}
